package com.njcky.utils.file;

import lombok.Cleanup;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 文件处理工具类
 */
public class FileUtils {
    //文件上传
    public static void fileUpload(MultipartFile[] files,String path){
        File filePath = new File(path);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        for (MultipartFile file : files) {
            // 将文件储存到您选择的位置
            try {
                File fileExist = new File(path, file.getOriginalFilename());
                if (fileExist.exists()) {
                    fileExist.delete();
                }
                @Cleanup//使用完InputStream后，关闭它。否则报Failed to perform cleanup of multipart items
                 InputStream inputStream = file.getInputStream();
                // 方式1:
//                file.transferTo(new File(path+ "/" + file.getOriginalFilename()));
                //方式2：
                Files.copy(inputStream, Paths.get(path + "/" + file.getOriginalFilename()));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
